import json
from rest_framework import serializers
from ..models.Department import Department
from ..utils.literUtils import emptyValue   

# 查询内容序列化
class DepListQuerySerializer(serializers.Serializer):
    name = serializers.CharField(required=False,allow_blank=True)
    zh_name = serializers.CharField(required=False,allow_blank=True)
    dep_code = serializers.CharField(required=False,allow_blank=True)
    email = serializers.CharField(required=False,allow_blank=True)
    contact_number = serializers.CharField(required=False,allow_blank=True)
    website = serializers.CharField(required=False,allow_blank=True)
    founded_date = serializers.CharField(required=False,allow_blank=True)
    description = serializers.CharField(required=False,allow_blank=True)
    dep_type = serializers.ListField(required=False)
    institution = serializers.CharField(required=False,allow_blank=True)

    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False,allow_blank=True)
    sort_order = serializers.CharField(required=False,allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "name" in attrs:
            attrs["name"] = attrs["name"].strip()
            if attrs["name"] == "": attrs.pop("name")
        if "zh_name" in attrs:
            attrs["zh_name"] = attrs["zh_name"].strip()
            if attrs["zh_name"] == "": attrs.pop("zh_name")
        if "dep_code" in attrs:
            attrs["dep_code"] = attrs["dep_code"].strip()
            if attrs["dep_code"] == "": attrs.pop("dep_code")
        if "email" in attrs:
            attrs["email"] = attrs["email"].strip()
            if attrs["email"] == "": attrs.pop("email")
        if "contact_number" in attrs:
            attrs["contact_number"] = attrs["contact_number"].strip()
            if attrs["contact_number"] == "": attrs.pop("contact_number")
        if "website" in attrs:
            attrs["website"] = attrs["website"].strip()
            if attrs["website"] == "": attrs.pop("website")
        if "founded_date" in attrs:
            attrs["founded_date"] = attrs["founded_date"].strip()
            if attrs["founded_date"] == "": attrs.pop("founded_date")
        if "description" in attrs:
            attrs["description"] = attrs["description"].strip()
            if attrs["description"] == "": attrs.pop("description")
        if "institution" in attrs:
            attrs["institution"] = attrs["institution"].strip()
            if attrs["institution"] == "": attrs.pop("institution")
        if "dep_type" in attrs:
            if len(attrs["dep_type"]) == 0: attrs.pop("dep_type")
        if ("name" not in attrs or attrs["name"] == "") and ("zh_name" not in attrs or attrs["zh_name"] == "") and\
           ("dep_code" not in attrs or attrs["dep_code"] == "")  and ("email" not in attrs or attrs["email"] == "") and\
           ("institution" not in attrs or attrs["institution"] == "") and ("dep_type" not in attrs or len(attrs["dep_type"]) == 0)  and\
           ("contact_number" not in attrs or attrs["contact_number"] == "") and ("website" not in attrs or attrs["website"] == "")  and\
           ("founded_date" not in attrs or attrs["founded_date"] == "") and ("description" not in attrs or attrs["description"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        else:
            if "current_page" not in attrs:
                attrs["current_page"] = 1
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs
    
    @classmethod
    def get_query_fields(self):
        return [{"title":"名称：", "dataIndex":"name", "type":"CharField"},
                {"title":"中文名：", "dataIndex":"zh_name", "type":"CharField"},
                {"title":"标识代码：", "dataIndex":"dep_code", "type":"CharField"},
                {"title":"联系邮箱：", "dataIndex":"email", "type":"CharField"},
                {"title":"联系电话：", "dataIndex":"contact_number", "type":"CharField"},
                {"title":"官方网站：", "dataIndex":"website", "type":"CharField"},
                {"title":"创立日期：", "dataIndex":"founded_date", "type":"CharField"},
                {"title":"所属类别：", "dataIndex":"dep_type", "type":"ForeignKey"},
                {"title":"描述：", "dataIndex":"description", "type":"CharField"},
                {"title":"所属机构：", "dataIndex":"institution", "type":"ManyToManyField"},]
        
        
# 用于输出查询时的数据


class DepListSerializer(serializers.ModelSerializer):
    dep_type = serializers.SerializerMethodField()
    institution = serializers.SerializerMethodField()

    class Meta:
        model = Department
        fields = ['uuid', 'name', 'zh_name', 'dep_code', 'contact_number',\
                  "email", "website", "founded_date", 'description',\
                  'dep_type', 'institution']
        
    def get_dep_type(self, obj): # obj: Literature类实例
        return "{}({})".format(obj.dep_type.zh_name, obj.dep_type.name) + "\n"
    
    def get_institution(self, obj):
        if obj.institution is None:
            return "未知"
        else:
            if emptyValue(obj.institution.zh_name):
                return obj.institution.name + "\n"
            else:
                return "{}({})".format(obj.institution.zh_name, obj.institution.name) + "\n"
    
    @classmethod
    def get_extra_fields_info(self):
        return [{"title":"所属类别", "dataIndex":"dep_type", "type":"CharField"},
                {"title":"所属机构", "dataIndex":"institution", "type":"CharField"},]